local getmetatable = getmetatable
local setmetatable = setmetatable
local module = module
local require = require
local print = print
local type = type
local error = error
local string = string
local pcall = pcall
local package = package

module('fit.ColumnFixture')
_VERSION='0.2'

local Fixture = require('fit.Fixture')

local function parseHeaders(self, heads)
    self.columnHeaders = {}
    i = 1
    while heads ~= nil do
        name = heads:text()
        self.columnHeaders[i] = name

        i = i + 1
        heads = heads.more
    end
end

-- doRows(Parse rows)
local function doRows(self, rows)
    self:parseHeaders(rows.parts)
    self.parent.doRows(self, rows.more)
end

local function doCell(self, cell, column)
    text = cell:text()
    header = self.columnHeaders[column]
    suffix = string.find(header, "%(%)$")
    if suffix then
        column = self[string.sub(header,1, suffix - 1)]
    else
        self[header] = text
    end

    if text == "" then
        self:check(cell, column)
    elseif column == nil then
        print("Ignoring cell: " .. text)
        self:ignore(cell)
    elseif type(column) == "function" then
        self:check(cell, column)
    end
end

-- Constructor ------------------------

function __call()
    local aColumnFixture = Fixture()

    -- We need access to some of the parent's functions
    aColumnFixture.parent = {}
    aColumnFixture.parent.doRows = aColumnFixture.doRows

    -- Expose Functions
    aColumnFixture.doCell = doCell
    aColumnFixture.doRows = doRows
    aColumnFixture.parseHeaders = parseHeaders

    return aColumnFixture
end

setmetatable(_M, _M)
